import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:beamer/beamer.dart';
import 'package:awak/common/utils/util_text.dart';
import 'package:awak/common/values/images.dart';
import 'package:awak/common/values/svg.dart';
import 'package:awak/common/repository/content_repository.dart';
import 'package:awak/common/repository/user_repository.dart';
import 'package:awak/common/models/content.dart';
import 'package:awak/common/models/user.dart';
import 'package:awak/page/community/content_data_holder.dart';
import 'package:awak/common/routers/router_names.dart';

class IssueProfilePage extends StatefulWidget {
  const IssueProfilePage({super.key});

  @override
  State<IssueProfilePage> createState() => _IssueProfilePageState();
}

class _IssueProfilePageState extends State<IssueProfilePage> {
  final ContentRepository _contentRepository = ContentRepository();
  final UserRepository _userRepository = UserRepository();

  List<Content> _userContents = [];
  User? _currentUser;
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    _loadUserContents();
  }

  Future<void> _loadUserContents() async {
    try {
      _currentUser = _userRepository.currentUser;

      if (_currentUser?.id != null) {
        // 获取用户发布的内容
        final contents = await _contentRepository.getContentsByUserId(
          _currentUser!.id!,
        );

        setState(() {
          _userContents = contents;
          _isLoading = false;
        });
      } else {
        setState(() {
          _userContents = [];
          _isLoading = false;
        });
      }
    } catch (e) {
      setState(() {
        _userContents = [];
        _isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFD7F349),
      body: Column(
        children: [
          SizedBox(height: 40.h),
          // 顶部导航栏
          Padding(
            padding: EdgeInsets.all(16.w),
            child: Row(
              children: [
                GestureDetector(
                  onTap: () {
                    Beamer.of(context).beamBack();
                  },
                  child: Icon(AwakSvg.back),
                ),
                Expanded(
                  child: Center(
                    child: Text('ISSUE', style: AwakText.titleStyle),
                  ),
                ),
                SizedBox(width: 20.w),
              ],
            ),
          ),
          SizedBox(height: 10.h),
          // 用户信息区域
          _buildUserInfoSection(),
          SizedBox(height: 20.h),
          // 内容列表
          Expanded(child: _buildContentList()),
        ],
      ),
    );
  }

  // 构建用户信息区域
  Widget _buildUserInfoSection() {
    if (_currentUser == null) {
      return Container();
    }

    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w),
      child: Row(
        children: [
          // 用户头像
          Container(
            width: 50.w,
            height: 50.h,
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              border: Border.all(color: Colors.black, width: 2.w),
              image: DecorationImage(
                image: AssetImage(_currentUser!.avatar ?? AwakImages.avatar),
                fit: BoxFit.cover,
              ),
            ),
          ),
          SizedBox(width: 12.w),
          // 用户信息
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  _currentUser!.nickname ?? _currentUser!.username,
                  style: AwakText.body18Style.copyWith(
                    color: Colors.black,
                    fontWeight: FontWeight.w700,
                  ),
                ),
                SizedBox(height: 4.h),
                Text(
                  _currentUser!.signature ?? 'Bright Enough To Be Seen',
                  style: AwakText.body14Style.copyWith(
                    color: Colors.black.withValues(alpha: 0.7),
                    fontWeight: FontWeight.w500,
                    fontSize: 12.sp,
                  ),
                ),
              ],
            ),
          ),
          // Issue标签
          GestureDetector(
            onTap: () {
              Beamer.of(context).beamToNamed(RouterNames.releaseContent);
            },
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 6.h),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(20.r),
                border: Border.all(color: Colors.black, width: 1.w),
              ),
              child: Row(
                children: [
                  Icon(AwakSvg.publish, size: 12.sp),
                  SizedBox(width: 4.w),
                  Text(
                    'Go to publish',
                    style: AwakText.body14Style.copyWith(
                      color: Colors.black,
                      fontWeight: FontWeight.w500,
                      fontSize: 12.sp,
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 构建内容列表
  Widget _buildContentList() {
    if (_isLoading) {
      return Center(child: CircularProgressIndicator());
    }

    if (_userContents.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.article_outlined,
              size: 64.w,
              color: Colors.black.withValues(alpha: 0.3),
            ),
            SizedBox(height: 16.h),
            Text(
              'No content published yet',
              style: AwakText.body16Style.copyWith(
                color: Colors.black.withValues(alpha: 0.5),
              ),
            ),
          ],
        ),
      );
    }

    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(20.r),
          topRight: Radius.circular(20.r),
        ),
      ),
      child: ListView.builder(
        padding: EdgeInsets.all(16.w),
        itemCount: _userContents.length,
        itemBuilder: (context, index) {
          return _buildContentCard(_userContents[index]);
        },
      ),
    );
  }

  // 构建内容卡片
  Widget _buildContentCard(Content content) {
    return GestureDetector(
      onTap: () {
        // 设置当前内容并跳转到内容详情页
        ContentDataHolder.setCurrentContent(content);
        Beamer.of(context).beamToNamed(RouterNames.detailContent);
      },
      child: Container(
        margin: EdgeInsets.only(bottom: 16.h),
        padding: EdgeInsets.all(16.w),
        decoration: BoxDecoration(
          color: Colors.transparent,
          borderRadius: BorderRadius.circular(12.r),
          // border: Border.all(color: Colors.black, width: 2.w),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 用户信息行
            Row(
              children: [
                Container(
                  width: 40.w,
                  height: 40.h,
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    border: Border.all(color: Colors.black, width: 2.w),
                    image: DecorationImage(
                      image: AssetImage(
                        _currentUser?.avatar ?? AwakImages.avatar,
                      ),
                      fit: BoxFit.cover,
                    ),
                  ),
                ),
                SizedBox(width: 12.w),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        _currentUser?.nickname ??
                            _currentUser?.username ??
                            'Sparse Star',
                        style: AwakText.body16Style.copyWith(
                          color: Colors.black,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                      Text(
                        _currentUser?.signature ?? 'Bright Enough To Be Seen',
                        style: AwakText.body14Style.copyWith(
                          color: Colors.black.withValues(alpha: 0.6),
                          fontSize: 12.sp,
                        ),
                      ),
                    ],
                  ),
                ),
                // Issue标签
                Container(
                  padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.h),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(100.r),
                    border: Border.all(color: Colors.black, width: 1.w),
                  ),
                  child: Row(
                    children: [
                      Icon(AwakSvg.report, size: 14.sp),
                      SizedBox(width: 4.w),
                      Text(
                        'Issue',
                        style: AwakText.body14Style.copyWith(
                          color: Colors.black,
                          fontWeight: FontWeight.w500,
                          fontSize: 12.sp,
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
            SizedBox(height: 12.h),
            // 内容图片
            Container(
              width: double.infinity,
              height: 223.h,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(12.r),
                // border: Border.all(color: Colors.black, width: 2.w),
                image: DecorationImage(
                  image: AssetImage(content.picture),
                  fit: BoxFit.cover,
                ),
              ),
            ),
            SizedBox(height: 12.h),
            // 内容描述
            Text(
              content.description,
              style: AwakText.body16Style.copyWith(
                color: Colors.black,
                fontWeight: FontWeight.w500,
                height: 1.4,
              ),
              maxLines: 2,
              overflow: TextOverflow.ellipsis,
            ),
          ],
        ),
      ),
    );
  }
}
